package com.ayoka.parenting.ui.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.ayoka.parenting.Constants;
import com.ayoka.parenting.R;
import com.ayoka.parenting.bean.NVCBean;
import com.ayoka.parenting.databinding.ActivityLoginByVerifyCodeBinding;
import com.ayoka.parenting.mvp.MVPBaseActivity;
import com.ayoka.parenting.utils.JSAndNative;
import com.ayoka.parenting.ui.html.SimpleWebViewActivity;
import com.ayoka.parenting.ui.main.MainActivity;
import com.ayoka.parenting.utils.CountDownEvent;
import com.ayoka.parenting.widget.ProgressWebView;
import com.jincp.common.base.APPActivityManager;
import com.jincp.common.model.ToolBarOptions;
import com.jincp.common.utils.LiveDataBus;
import com.jincp.common.utils.PatternCheck;
import com.jincp.common.utils.StringUtil;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebViewClient;

import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.LinearLayout;

import java.util.Observable;
import java.util.Observer;

/**
 * @ProjectName: MVPPlugin.
 * @ClassName: LoginByVerifyCodeActivity.
 * @Description: .
 * @Author: jincp.
 * @CreateDate: 2019/10/10 18:17.
 */
public class LoginByVerifyCodeActivity extends MVPBaseActivity<ActivityLoginByVerifyCodeBinding, LoginContract.View, LoginPresenter> implements LoginContract.View, Observer, ProgressWebView.ActivityView {


    public static void start(Activity activity) {
        APPActivityManager.getInstance().finish(MainActivity.class);
        Intent intent = new Intent(activity, LoginByVerifyCodeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }

    private String mobile;
    private String verifyCode;

    private int operateType = 0;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_login_by_verify_code;
    }

    @Override
    protected void initViews() {
        mDataBinding.btnLogin.setOnClickListener(this);
        mDataBinding.btnGetVerifyCode.setOnClickListener(this);
        mDataBinding.tvServiceAgreement.setOnClickListener(this);

        mDataBinding.cbNext.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mDataBinding.btnLogin.setEnabled(isChecked);
            }
        });
        mDataBinding.progressWebview.setActivityView(this);
        mDataBinding.progressWebview.addJavascriptInterface(new JSAndNative(), "ayoka");
        mDataBinding.progressWebview.loadUrl(Constants.VERIFY_WEBVIEW_URL);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        LiveDataBus.getInstance().with("JSAndNative", String.class).observe(this, new android.arch.lifecycle.Observer<String>() {
            @Override
            public void onChanged(@Nullable String token) {
                if (operateType == 0) {
                    mDataBinding.btnGetVerifyCode.setEnabled(true);
                    if (!TextUtils.isEmpty(token) && mPresenter != null) {
                        mPresenter.sendVerifyCode(token, mobile);
                    }
                } else if (operateType == 1) {
                    mDataBinding.btnLogin.setEnabled(true);
                    if (!TextUtils.isEmpty(token) && mPresenter != null) {
                        mPresenter.login(token, mobile, verifyCode);
                    }
                }
            }
        });
    }

    @Override
    protected LoginPresenter getPresenter() {
        return new LoginPresenter();
    }

    @Override
    public void onClick(View view) {
        if (view == mDataBinding.btnGetVerifyCode) {
            operateType = 0;
            if (mDataBinding.edtMobile.length() == 0) {
                showToast(getString(R.string.input_mobile));
                return;
            }
            mobile = mDataBinding.edtMobile.getText().toString().trim();
            if (!PatternCheck.isMobile(mobile)) {
                showToast(getString(R.string.input_correct_mobile));
                return;
            }
            //通过java代码调用js方法
            mDataBinding.progressWebview.loadUrl("javascript:getNVCValue()");
            mDataBinding.btnGetVerifyCode.setEnabled(false);
        } else if (view == mDataBinding.btnLogin) {
            operateType = 1;
            if (mDataBinding.edtMobile.length() == 0) {
                showToast(getString(R.string.input_mobile));
                return;
            }
            String mobile = mDataBinding.edtMobile.getText().toString().trim();
            if (!PatternCheck.isMobile(mobile)) {
                showToast(getString(R.string.input_correct_mobile));
                return;
            }
            if (mDataBinding.edtVerifyCode.length() == 0) {
                showToast(getString(R.string.input_verify_code));
                return;
            }
            verifyCode = mDataBinding.edtVerifyCode.getText().toString().trim();
            //通过java代码调用js方法
            mDataBinding.progressWebview.loadUrl("javascript:getNVCValue()");
            mDataBinding.btnLogin.setEnabled(false);
        } else if (view == mDataBinding.tvServiceAgreement) {
            ToolBarOptions options = new ToolBarOptions("哈巴教练协议");
            SimpleWebViewActivity.start(this, Constants.SERVICE_AGREEMENT_URL, "", options);
        }
    }

    @Override
    public void onSendVerifyCodeCallback(NVCBean nvcBean) {
        if (nvcBean != null) {
            if (nvcBean.BizCode == 100 || nvcBean.BizCode == 200) {
                CountDownEvent.getInstance().addObserver(this);
                CountDownEvent.getInstance().start(120 * 1000);
                showToast("发送成功！请注意查收");
                //通过java代码调用js方法
                mDataBinding.progressWebview.loadUrl("javascript:resetNVC()");
            } else {
                try {
                    mDataBinding.layoutMainContainer.removeView(mDataBinding.progressWebview);
                } catch (Exception e){
                    e.printStackTrace();
                }
                if (mPresenter != null) {
                    mPresenter.showWebViewVerifyDialog(getSupportFragmentManager(), nvcBean.BizCode, mDataBinding.progressWebview);
                    mDataBinding.btnGetVerifyCode.setEnabled(true);
                }
            }
        } else {
            //通过java代码调用js方法
            mDataBinding.progressWebview.loadUrl("javascript:resetNVC()");
            mDataBinding.btnGetVerifyCode.setEnabled(true);
        }
    }

    @Override
    public void onLoginCallback(NVCBean nvcBean) {
        if (nvcBean != null) {
            if (nvcBean.BizCode == 100 || nvcBean.BizCode == 200) {
                MainActivity.start(this);
                finish();
            } else if (nvcBean.BizCode == 800 || nvcBean.BizCode == 900) {
                showToast(getString(R.string.register_failed));
            } else {
                if (mPresenter != null) {
                    mDataBinding.layoutMainContainer.removeView(mDataBinding.progressWebview);
                    mPresenter.showWebViewVerifyDialog(getSupportFragmentManager(), nvcBean.BizCode, mDataBinding.progressWebview);
                    mDataBinding.btnLogin.setEnabled(true);
                }
            }
        } else {
            mDataBinding.btnLogin.setEnabled(true);
        }
    }

    @Override
    public void onDialogDismiss(DialogFragment dialog) {
        if (dialog instanceof WebViewVerifyDialog) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0);
            mDataBinding.layoutMainContainer.addView(mDataBinding.progressWebview, params);
            mDataBinding.btnGetVerifyCode.setEnabled(true);
        }
    }

    @Override
    public void update(Observable observable, Object arg) {
        if (observable instanceof CountDownEvent) {
            long leftTime = (long) arg;
            if (leftTime > 0) {
                String text = StringUtil.formatString(R.string.format_resend, leftTime / 1000);
                mDataBinding.btnGetVerifyCode.setText(text);
                mDataBinding.btnGetVerifyCode.setEnabled(false);
            } else {
                mDataBinding.btnGetVerifyCode.setText(R.string.get_verify_code);
                mDataBinding.btnGetVerifyCode.setEnabled(true);
            }
        }
    }


    @Override
    protected void onDestroy() {
        CountDownEvent.getInstance().deleteObserver(this);
        CountDownEvent.getInstance().cancel();
        super.onDestroy();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public WebViewClient getWebViewClient() {
        return null;
    }

    @Override
    public WebChromeClient getWebChromeClient() {
        return null;
    }
}
